<template>
  <div>

    <!-- 表单内容 -->
    <el-form :model="form" label-width="120px">
      <h2>资产报修</h2>
      <h6>基础信息</h6>
      <el-form-item label="标题" required>
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">

          <el-form-item label="报修单号" required>
            <el-input v-model="form.reportNum" readonly></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="12">

          <el-form-item label="申请日期" required>
            <el-date-picker v-model="form.applyDate" type="date" :formatter="dataFormat"></el-date-picker>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报修人" required>
            <el-select @change="handleApplicantChange" v-model="form.applicantId" filterable placeholder="请输入报修人">
              <el-option v-for="applicant in applicantList" :key="applicant.id" :label="applicant.name"
                :value="applicant.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item label="申请部门" required>
            <el-input v-model="form.departName" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">

          <el-form-item label="维保厂商" required>
            <el-select @change="handleVendorChange" v-model="form.vendorId" filterable placeholder="请选择维保厂商">
              <el-option v-for="vendor in vendorList" :key="vendor.id" :label="vendor.name" :value="vendor.id">
              </el-option>
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" required>
            <el-input v-model="form.name" placeholder="请输入联系人" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系方式" required>
            <el-input v-model="form.phone" placeholder="请输入联系方式" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="报修内容" required>
        <el-input type="textarea" v-model="form.repariDetal" placeholder="请输入报修内容"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"></el-input>
      </el-form-item>
      <div class="button-container">
        <!-- 底部固定按钮 -->
        <el-button type="primary" class="fixed-button" @click="saveForm()">保存</el-button>
        <el-button type="info" class="fixed-button" @click="outForm()">关闭</el-button>
      </div>


      <h6>资产明细</h6>
      <el-button @click="batchAdd()" type="primary" size="small">添加</el-button>
      <el-button @click="batchRemove()" type="primary" size="small">移除</el-button>


      <el-table @selection-change="handleSelectionChange" ref="multipleTable" :data="detailList" border
        style="width: 100%" row-key="id">
        <!-- 设置是否保留选择 -->
        <el-table-column type="selection" fixed width="50" :reserve-selection="true">
        </el-table-column>
        <!-- 序号列 -->
        <el-table-column fixed prop="id" label="序号" width="50">
        </el-table-column>

        <el-table-column prop="number" label="资产编码">
        </el-table-column>
        <el-table-column prop="assetName" label="资产名称">
        </el-table-column>
        <el-table-column prop="model" label="规格型号">
        </el-table-column>
        <el-table-column prop="assetCategoryName" label="资产分类">
        </el-table-column>
        <el-table-column prop="unit" label="单位">
        </el-table-column>
        <el-table-column prop="adminName" label="管理人">
        </el-table-column>
        <el-table-column prop="userName" label="使用人">
        </el-table-column>
        <el-table-column prop="nowStorageLocationName" label="存放地点">
        </el-table-column>
        <el-table-column prop="assetStatus" label="状态">
          <template slot-scope="scope">
            {{ getAssetStatusText(scope.row.assetStatus) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" prop="action" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleRemove(scope.row.id,scope.$index)" type="text" size="small">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <!-- 使用其他页面的组件 -->
        <Detail ref="detail" @batchAdd="handleBatchAdd" :dialogFormVisible="dialogFormVisible" :searchMap="searchMap"
          :detailList="detailList" :detailCount="detailCount" :selectedItems="selectedItems">
        </Detail>
      </div>

    </el-form>
  </div>
</template>

<script>
// 导入其他页面的组件
import assetReportService from '@/api/asset-report';
import Detail from '@/views/mainten/report/detail.vue';
//导入日期组件
import moment from 'moment'
import userService from '@/api/user';
import maintenVendorApi from '@/api/mainten-vendor';
import departmentService from '@/api/depart';
import maintenPersonnelApi from '@/api/mainten-personal';

export default {

  components: {
    Detail
  },

  data() {
    return {
      applicantList: [],
      vendorList: [],
      editList: [],
      dialogFormVisible: false,
      searchMap: {},
      detailList: [],
      detailCount: 0,
      selectedItems: [],
      form: {
        id: '',
        departName: '',
        name: '',
        phone: '',
        assetReportNum: ''
      },
      forms: {
        id: '',
        reportNum: '',
      },
      ids: [],

    };
  },
  mounted() {
    console.log(this.$route.query.reportNum);
    this.form.assetReportNum = this.$route.query.reportNum
    this.getEditList();
    this.getDetailList();
    //报修人查询
    this.getApplicantList();
    //供应商查询
    this.getVendorList();
  },
  created() {

  },
  methods: {
    getDetailList() {
      assetReportService.findDetail(this.form).then(response => {
        this.detailList = response.data;
        this.detailCount = response.count;
      });
    },
    getEditList() {
      assetReportService.findByAssetReportNum(this.form.assetReportNum).then(response => {
        console.log('response', response.data);
        this.editList = response.data[0];
        this.form = { ...this.editList }; // 使用对象展开运算符来复制属性
        this.handleVendorChange(this.form.vendorId);
        this.handleApplicantChange(this.form.applicantId);
      })
    },
    handleSelectionChange(val) {
      this.selectedItems = val; // 更新用户选择的项
      console.log(this.selectedItems);
    },
    batchRemove() {
      assetReportService.findAll().then(response => {
        // 获取用户选择的 assetId 列表
        let selectedAssetIds = this.selectedItems.map(item => item.id);

        // 在 response.data 中查找匹配的资产
        let matchedAssets = response.data.filter(item =>
          selectedAssetIds.includes(item.assetId) && item.reportNum === this.$route.query.reportNum
        );
        this.$confirm('是否要删除该条目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击了“确定”按钮，执行删除操作
          assetReportService.batchRemove( {ids: matchedAssets.map(item => item.id) }).then(response => {
            // 过滤掉被选中的项
            this.detailList = this.detailList.filter(item => !this.selectedItems.includes(item));
            this.selectedItems = []; // 清空用户选择的项
            this.$refs.multipleTable.clearSelection(); // 清除表格的选择状态
            console.log('批量删除后的detailList:', this.detailList);
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }).catch(error => {
            // 处理删除失败的情况
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          });
        }).catch(() => {
          // 用户点击了“取消”按钮或关闭了弹窗
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      })
    },
    handleVendorChange(maintenVendorId) {
      maintenPersonnelApi.findPersonByVendorId(maintenVendorId).then(res => {
        if (res.data.length == 0) {
          this.form.maintenPersonnelId = ''
          this.form.maintenPersonnelName = ''
          return
        }
        this.form.name = res.data[0].name
        this.form.phone = res.data[0].phone
      }
      )
    },
    handleApplicantChange(applicantId) {
      // 根据 applicantId 查询用户所属部门
      userService.find(applicantId).then(response => {
        const departId = response.data.departId;
        departmentService.find(departId).then(response => {
          console.log('departmentService', response.data);
          const departmentName = response.data.name;
          // 将部门名称填入申请部门的输入框中
          console.log('departmentName', departmentName);
          if (response.data.length === 0) {
            this.form.departName = '';
          } else {
            this.form.departName = departmentName;
          }
        })
      })
    },
    getApplicantList() {
      userService.findAll().then(response => {
        this.applicantList = response.data;
      })
    },
    getVendorList() {
      maintenVendorApi.findAll().then(response => {
        this.vendorList = response.data;
      })
    },
    //增加一个格式化日期的方法
    dataFormat(row, column) {
      let date = row[column.property]
      if (date == undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD hh:mm:ss')
    },
    outForm() {
      this.$router.push('/mainten/report');
    },
    getAssetStatusText(status) {
      // 根据状态返回按钮文本
      switch (status) {
        case 1:
          return '使用';
        case 2:
          return '闲置';
        case 3:
          return '借用';
        case 4:
          return '调拨';
        default:
          return '未知状态';
      }
    },
    batchAdd() {
      this.$refs.detail.getDetail();
    },
    handleBatchAdd(items) {
      // 在这里处理来自子组件的 items
      this.detailList = items;
    },
    handleRemove(assetId, index) {
      console.log('assetId', assetId);
      console.log('this。form', this.$route.query.reportNum);
      assetReportService.findAll().then(response => {
        console.log('数据',response.data);
        let asset = response.data.find(item => item.assetId === assetId && item.reportNum ===this.$route.query.reportNum);
        console.log('asset', asset);
        this.$confirm('是否要删除该条目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击了“确定”按钮，执行删除操作
          assetReportService.delete(asset.id).then(response => {
            //删除数据项
            this.detailList.splice(index, 1);
            console.log('Updated detailList:', this.detailList);
            this.selectedItems = this.detailList;
            console.log('Selected items:', this.selectedItems);
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }).catch(error => {
            // 处理删除失败的情况
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          });
        }).catch(() => {
          // 用户点击了“取消”按钮或关闭了弹窗
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      })
    },
    saveForm() {
      // 提取 id 并存储在 ids 数组中
      this.ids = this.detailList.map(item => item.id);
      this.forms = this.ids.map(assetId => {
        const newForm = { ...this.form, assetId: assetId };
        return newForm;
      });
      assetReportService.findAll().then((res) => {
        var filterList = res.data.filter(item => item.reportNum === this.forms[0].reportNum)
        filterList.forEach(item => {
          this.forms.forEach(form => {
            if (item.assetId === form.assetId) {
              form.id = item.id
            }
          })
        })
        assetReportService.batchUpdate(this.forms)
          .then((res) => {
            if (res.code == 0) {
              this.$message.success('修改成功');
              this.$router.push('/mainten/report');
            } else {
              this.$message.error('修改失败');
            }
          })
      })
      console.log('forms', this.forms);
     
    },
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
}

/* 底部按钮容器样式 */
.button-container {
  position: fixed;
  right: 20px;
  bottom: 20px;
  display: flex;
  gap: 10px;
  /* 控制按钮之间的间距 */
  z-index: 1000;
  /* 确保按钮在最上层 */
}

.fixed-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.fixed-button:hover {
  background-color: #0056b3;
}

.fixed-button[type="info"] {
  background-color: #909399;
}
</style>